import Permissions from "@/constant/permission";
import { RouteName } from "@/constant/route";
import { ApiRouteRecord } from "@/types/entity/route";
import { arrayToTreeArray } from "@/utils/arrayUtils";
import axios from "axios";
import { cloneDeep, has, isString } from "lodash-es";
import { RouteRecordRaw } from "vue-router";

const useUserStore = defineStore(
  "user",
  () => {
    const user = ref<any>({ userId: 2 });
    const authRoutes = ref<ApiRouteRecord[]>([]);
    const permissions = ref(["*:*:*"]);
    const views = import.meta.glob("@/views/**/index.vue");

    const getUser = computed(() => user.value);
    const getPermissions = computed(() => permissions.value);
    const getAuthRoutes = computed(() => {
      const routes = cloneDeep(unref(authRoutes)).map((route: any) => {
        if (route.component && isString(route.component))
          route.component = views[`/src/views${route.component}`];
        return route;
      });
      const treeRoutesArray = arrayToTreeArray<RouteRecordRaw>(routes);
      treeRoutesArray
        .sort((a, b) => (a.meta?.order ?? 0) - (b.meta?.order ?? 0))
        .forEach(
          (route) =>
            route.children &&
            route.children.sort((a, b) => (a.meta?.order ?? 0) - (b.meta?.order ?? 0))
        );
      return treeRoutesArray;
    });

    const login = (_loginInfo?: any) => {
      return true;
    };
    const logout = () => {};
    const setAuthRoutes = (routes: ApiRouteRecord[]) => {
      authRoutes.value = [
        {
          id: 99999,
          pid: null,
          name: RouteName.CONSOLE,
          path: "console",
          component: "/console/index.vue",
          meta: { label: "控制台", icon: "ph:squares-four" },
        } as any,
        ...routes,
      ];
    };
    const fetchUserAuthRoutes = async () => {
      if (!has(unref(user), "userId")) return;
      const { data } = await axios.get("/api/auth-routes");
      setAuthRoutes(data.data);
    };
    const hasPermission = (needPermission?: string) => {
      if (!needPermission) return false;
      if (unref(permissions).includes(Permissions.ALL)) return true;
      return unref(permissions).includes(needPermission);
    };
    const hasAllPermissions = (needPermissions?: string[]) => {
      if (!needPermissions) return false;
      if (unref(permissions).includes(Permissions.ALL)) return true;
      return needPermissions.every((permission) => unref(permissions).includes(permission));
    };
    const hasOneOfPermission = (needPermissions?: string[]) => {
      if (!needPermissions) return false;
      if (unref(permissions).includes(Permissions.ALL)) return true;
      return needPermissions.some((permission) => unref(permissions).includes(permission));
    };

    return {
      authRoutes,
      getUser,
      getAuthRoutes,
      getPermissions,
      login,
      logout,
      setAuthRoutes,
      fetchUserAuthRoutes,
      hasPermission,
      hasAllPermissions,
      hasOneOfPermission,
    };
  },
  {
    persist: true,
  }
);

export default useUserStore;
